﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MyJoystic;
public class D05_Character3 : MonoBehaviour
{
    private CharacterController cha;

    public float normalY = -5;//正常的y速度
    private float y; //当前的y速度
    public float jumpY = 5;//起跳时候的y速度
    public float decreaseY = 5f;//起跳后每秒减少的y速度
    public int Canjump = 2;//可以连续跳的次数
    private int money = 0;//每次跳跃都会消耗money
    private void Start()
    {
        y = normalY;
        cha = GetComponent<CharacterController>();
    }

    private void Update()
    {
        Vector3 dir = Joystic.instance.Value;

        Jump();

        dir.y = y;
        cha.Move(dir * 5 * Time.deltaTime);//移动,不自动使用重力,不自动使用Time.deltaTime

        dir.y = 0;
        if (dir.sqrMagnitude > 0.001f)//如果向量太小就返回
        {
            transform.rotation = Quaternion.LookRotation(dir);    //设置旋转|
        }
    }

    private void Jump()
    {
        //控制y就可以跳跃
        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (cha.isGrounded)//判断角色控制器是否在地板上,防止连续跳跃
            {
                y = jumpY;
                money = Canjump;
                money -= 1;
            }
            else//在空中
            {
                if (money > 0)
                {
                    y = jumpY;
                    money -= 1;
                }
            }
        }
        //让y衰减就可以让y再次回到-5
        if (y > normalY)
        {
            y -= decreaseY * Time.deltaTime;
        }
    }
}